'use strict';

const moment = require('moment');

module.exports = app => {
  const { Sequelize } = app;

  const Users = app.model.define('Users', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: Sequelize.INTEGER
    },
    openId: {
      allowNull: false,
      type: Sequelize.STRING(100)
    },
    avatarUrl: {
      allowNull: false,
      type: Sequelize.STRING(255),
      defaultValue: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
    },
    city: {
      allowNull: false,
      type: Sequelize.STRING(16)
    },
    gender: {
      allowNull: false,
      type: Sequelize.INTEGER(1)
    },
    nickname: {
      allowNull: false,
      type: Sequelize.STRING(16)
    },
    province: {
      allowNull: false,
      type: Sequelize.STRING(16)
    },
    appId: {
      allowNull: false,
      type: Sequelize.STRING(100),
      defaultValue: ''
    },
    skey: {
      allowNull: false,
      type: Sequelize.STRING(100),
      defaultValue: ''
    },
    sessionKey: {
      allowNull: false,
      type: Sequelize.STRING(100),
      defaultValue: ''
    },
    totalIn: {
      allowNull: false,
      type: Sequelize.INTEGER,
      defaultValue: 0
    },
    amount: {
      allowNull: false,
      type: Sequelize.INTEGER,
      defaultValue: 0
    },
    winning: {
      allowNull: false,
      type: Sequelize.INTEGER,
      defaultValue: 0
    },
    launch: {
      allowNull: false,
      type: Sequelize.INTEGER,
      defaultValue: 0
    },
    join: {
      allowNull: false,
      type: Sequelize.INTEGER,
      defaultValue: 0
    },
    type: {
      allowNull: false,
      type: Sequelize.INTEGER(1)
    },
    createdAt: {
      allowNull: false,
      type: Sequelize.DATE,
      get() { return moment(this.getDataValue('createdAt')).format('YYYY-MM-DD HH:mm') }
    },
    updatedAt: {
      allowNull: false,
      type: Sequelize.DATE,
      get() { return moment(this.getDataValue('updatedAt')).format('YYYY-MM-DD HH:mm') }
    },
    deletedAt: {
      type: Sequelize.DATE
    }
  }, {
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [{
      unique: true,
      fields: ['openId']
    }],
    comment: '用户表',
  });

  Users.associate = models => {
    Users.hasMany(app.model.Integrals, {
      foreignKey: 'userId',
      sourceKey: 'id',
    });

    Users.belongsToMany(app.model.Goods, {
      through: 'UsersGoods',
      foreignKey: 'userId',
    })
  }

  return Users;

};